package com.example.springssm.service.impl;

import com.example.springssm.bean.Employee;
import com.example.springssm.common.PageResult;
import com.example.springssm.mapper.EmployeeMapper;
import com.example.springssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public Employee getEmployeeById(Long id) {
        return employeeMapper.selectById(id);
    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @Override
    public List<Employee> getAllEmployees() {
        return employeeMapper.selectAll();
    }

    /**
     * 新增员工
     *
     * @param employee
     */
    @Override
    public void addEmployee(Employee employee) {
        employeeMapper.insert(employee);
    }

    /**
     * 更新员工
     *
     * @param employee
     */
    @Override
    public void updateEmployee(Employee employee) {
        employeeMapper.update(employee);
    }

    /**
     * 删除员工
     *
     * @param id
     */
    @Override
    public void deleteEmployee(Long id) {
        employeeMapper.deleteById(id);
    }

    @Override
    public PageResult<Employee> getEmployeesByPage(int pageNum, int pageSize) {
        // 1. 计算偏移量 offset = (pageNum - 1) * pageSize
        int offset = (pageNum - 1) * pageSize;
        // 2. 查询当前页数据
        List<Employee> list = employeeMapper.selectByPage(offset, pageSize);
        // 3. 查询总记录数
        int total = employeeMapper.countTotal();
        // 4. 计算总页数 totalPage = (total + pageSize - 1) / pageSize
        int totalPage = (total + pageSize - 1) / pageSize;
        // 5. 封装分页结果对象 (需要创建 PageResult 类)
        PageResult<Employee> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);
        pageResult.setTotalPages(totalPage);
        pageResult.setList(list);
        return pageResult;
    }
}
